<template>
  <div class="security-reporting-container">
    <el-card class="reporting-card">
      <template #header>
        <div class="card-header">
          <h2>安全报告生成</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateReportDialog = true">
              <el-icon><Plus /></el-icon>
              新建报告
            </el-button>
            <el-button @click="refreshReports">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 报告列表搜索和筛选 -->
      <div class="search-filter-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索报告名称或描述"
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filterReportType"
              placeholder="选择报告类型"
              clearable
              @change="handleFilter"
            >
              <el-option label="扫描报告" value="scan" />
              <el-option label="漏洞聚合报告" value="vulnerability" />
              <el-option label="合规报告" value="compliance" />
              <el-option label="自定义报告" value="custom" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleFilter"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="resetFilters">
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 报告列表 -->
      <div class="report-list-container">
        <el-table
          v-loading="loading"
          :data="paginatedReports"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-dblclick="viewReportDetails"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="报告名称" min-width="250">
            <template #default="scope">
              <div class="report-name-cell">
                <div class="report-name">{{ scope.row.name }}</div>
                <div class="report-description">{{ truncateText(scope.row.description, 80) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="报告类型" width="120">
            <template #default="scope">
              <el-tag :type="getReportTypeTag(scope.row.type)">
                {{ getReportTypeLabel(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="报告状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getReportStatusTag(scope.row.status)" effect="plain">
                {{ getReportStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="报告格式" width="120">
            <template #default="scope">
              <div class="report-formats">
                <el-tag size="small" v-for="format in scope.row.formats" :key="format" effect="dark" class="format-tag">
                  {{ getFormatLabel(format) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="包含漏洞" width="100" align="center">
            <template #default="scope">
              <div class="vulnerability-stats">
                <div v-if="scope.row.vulnerabilityStats">
                  <span class="critical-count" :title="`严重: ${scope.row.vulnerabilityStats.critical}`">
                    <el-icon><WarningFilled /></el-icon> {{ scope.row.vulnerabilityStats.critical }}
                  </span>
                  <span class="high-count" :title="`高危: ${scope.row.vulnerabilityStats.high}`">
                    <el-icon><Warning /></el-icon> {{ scope.row.vulnerabilityStats.high }}
                  </span>
                  <span class="medium-count" :title="`中危: ${scope.row.vulnerabilityStats.medium}`">
                    <el-icon><InfoFilled /></el-icon> {{ scope.row.vulnerabilityStats.medium }}
                  </span>
                  <span class="low-count" :title="`低危: ${scope.row.vulnerabilityStats.low}`">
                    <el-icon><CircleInfo /></el-icon> {{ scope.row.vulnerabilityStats.low }}
                  </span>
                </div>
                <span v-else>-</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="generatedBy" label="生成人" width="100">
            <template #default="scope">
              <div class="generated-by">
                <el-avatar :size="24" :src="getUserAvatar(scope.row.generatedBy)">
                  {{ getUserInitial(scope.row.generatedBy) }}
                </el-avatar>
                <span>{{ getUserName(scope.row.generatedBy) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="生成时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                v-if="scope.row.status === 'completed'"
                @click="downloadReport(scope.row)"
                size="small"
                title="下载报告"
              >
                <el-icon><Download /></el-icon>
              </el-button>
              <el-button
                type="primary"
                link
                @click="viewReportDetails(scope.row)"
                size="small"
                title="查看详情"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button
                type="primary"
                link
                v-if="scope.row.status === 'completed'"
                @click="shareReport(scope.row)"
                size="small"
                title="分享报告"
              >
                <el-icon><Share /></el-icon>
              </el-button>
              <el-button
                type="danger"
                link
                @click="deleteReport(scope.row)"
                size="small"
                title="删除报告"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredReports.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建报告对话框 -->
    <el-dialog
      v-model="showCreateReportDialog"
      title="新建安全报告"
      width="700px"
      @close="resetCreateReportForm"
    >
      <el-form
        ref="createReportFormRef"
        :model="createReportForm"
        :rules="createReportFormRules"
        label-width="120px"
      >
        <el-form-item label="报告名称" prop="name">
          <el-input
            v-model="createReportForm.name"
            placeholder="请输入报告名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="报告描述" prop="description">
          <el-input
            v-model="createReportForm.description"
            type="textarea"
            placeholder="请输入报告描述"
            :rows="2"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="报告类型" prop="type">
          <el-radio-group v-model="createReportForm.type">
            <el-radio :label="'scan'">扫描报告</el-radio>
            <el-radio :label="'vulnerability'">漏洞聚合报告</el-radio>
            <el-radio :label="'compliance'">合规报告</el-radio>
            <el-radio :label="'custom'">自定义报告</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="报告格式" prop="formats">
          <el-checkbox-group v-model="createReportForm.formats">
            <el-checkbox :label="'pdf'">PDF</el-checkbox>
            <el-checkbox :label="'html'">HTML</el-checkbox>
            <el-checkbox :label="'excel'">Excel</el-checkbox>
            <el-checkbox :label="'json'">JSON</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="包含内容" prop="contentSections" v-if="createReportForm.type !== 'compliance'">
          <el-checkbox-group v-model="createReportForm.contentSections">
            <el-checkbox :label="'executive_summary'">执行摘要</el-checkbox>
            <el-checkbox :label="'vulnerability_summary'">漏洞摘要</el-checkbox>
            <el-checkbox :label="'detailed_findings'">详细发现</el-checkbox>
            <el-checkbox :label="'remediation_guidance'">修复建议</el-checkbox>
            <el-checkbox :label="'risk_assessment'">风险评估</el-checkbox>
            <el-checkbox :label="'technical_details'">技术细节</el-checkbox>
            <el-checkbox :label="'appendices'">附录</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="合规标准" prop="complianceStandards" v-if="createReportForm.type === 'compliance'">
          <el-select
            v-model="createReportForm.complianceStandards"
            multiple
            filterable
            placeholder="请选择合规标准"
          >
            <el-option label="CIS Benchmark" value="cis" />
            <el-option label="PCI DSS" value="pci_dss" />
            <el-option label="NIST" value="nist" />
            <el-option label="GDPR" value="gdpr" />
            <el-option label="ISO 27001" value="iso_27001" />
            <el-option label="HIPAA" value="hipaa" />
            <el-option label="自定义标准" value="custom" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报告数据范围" prop="dataRange">
          <el-tabs v-model="createReportForm.dataRangeType">
            <el-tab-pane label="扫描任务" name="scan_tasks">
              <el-select
                v-model="createReportForm.selectedScanTasks"
                multiple
                filterable
                placeholder="请选择扫描任务"
                style="width: 100%"
              >
                <el-option
                  v-for="task in availableScanTasks"
                  :key="task.id"
                  :label="`${task.name} (${formatDate(task.completedAt)})`"
                  :value="task.id"
                />
              </el-select>
            </el-tab-pane>
            <el-tab-pane label="时间范围" name="date_range">
              <el-date-picker
                v-model="createReportForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-tab-pane>
            <el-tab-pane label="资产范围" name="assets">
              <el-select
                v-model="createReportForm.selectedAssets"
                multiple
                filterable
                placeholder="请选择资产"
                style="width: 100%"
              >
                <el-option
                  v-for="asset in availableAssets"
                  :key="asset.id"
                  :label="asset.name"
                  :value="asset.id"
                />
              </el-select>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        
        <el-form-item label="严重程度筛选" prop="severityFilter">
          <el-checkbox-group v-model="createReportForm.severityFilter">
            <el-checkbox :label="'critical'">严重</el-checkbox>
            <el-checkbox :label="'high'">高危</el-checkbox>
            <el-checkbox :label="'medium'">中危</el-checkbox>
            <el-checkbox :label="'low'">低危</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="状态筛选" prop="statusFilter">
          <el-checkbox-group v-model="createReportForm.statusFilter">
            <el-checkbox :label="'new'">待确认</el-checkbox>
            <el-checkbox :label="'confirmed'">已确认</el-checkbox>
            <el-checkbox :label="'in_progress'">处理中</el-checkbox>
            <el-checkbox :label="'fixed'">已修复</el-checkbox>
            <el-checkbox :label="'verified'">已验证</el-checkbox>
            <el-checkbox :label="'closed'">已关闭</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="报告模板" prop="templateId">
          <el-select
            v-model="createReportForm.templateId"
            placeholder="选择报告模板（可选）"
            allow-create
            filterable
          >
            <el-option
              v-for="template in reportTemplates"
              :key="template.id"
              :label="template.name"
              :value="template.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="报告选项">
          <el-checkbox v-model="createReportForm.includeStatistics">包含统计图表</el-checkbox>
          <el-checkbox v-model="createReportForm.includeRemediationTime">包含修复时间线</el-checkbox>
          <el-checkbox v-model="createReportForm.includeRiskScore">包含风险评分</el-checkbox>
          <el-checkbox v-model="createReportForm.anonymizeData">匿名化敏感数据</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateReportDialog = false">取消</el-button>
          <el-button type="primary" @click="createReport">创建报告</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 报告详情对话框 -->
    <el-dialog
      v-model="showReportDetailsDialog"
      :title="`报告详情 - ${selectedReport?.name}`"
      width="800px"
    >
      <div class="report-details">
        <div class="details-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="报告名称">{{ selectedReport?.name }}</el-descriptions-item>
            <el-descriptions-item label="报告ID">{{ selectedReport?.id }}</el-descriptions-item>
            <el-descriptions-item label="报告类型">
              <el-tag :type="getReportTypeTag(selectedReport?.type)">
                {{ getReportTypeLabel(selectedReport?.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="报告状态">
              <el-tag :type="getReportStatusTag(selectedReport?.status)" effect="plain">
                {{ getReportStatusLabel(selectedReport?.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="报告格式" :span="2">
              <div class="report-formats">
                <el-tag size="small" v-for="format in selectedReport?.formats" :key="format" effect="dark" class="format-tag">
                  {{ getFormatLabel(format) }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="生成人">
              <div class="generated-by">
                <el-avatar :size="24" :src="getUserAvatar(selectedReport?.generatedBy)">
                  {{ getUserInitial(selectedReport?.generatedBy) }}
                </el-avatar>
                <span>{{ getUserName(selectedReport?.generatedBy) }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="生成时间">{{ formatDateTime(selectedReport?.createdAt) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatDateTime(selectedReport?.updatedAt) }}</el-descriptions-item>
            <el-descriptions-item label="生成耗时">{{ selectedReport?.generationTime || '-' }} 秒</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="details-section">
          <h3>漏洞统计</h3>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-statistic :value="selectedReport?.vulnerabilityStats?.critical || 0" title="严重" :precision="0">
                <template #suffix>
                  <el-icon><WarningFilled /></el-icon>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="6">
              <el-statistic :value="selectedReport?.vulnerabilityStats?.high || 0" title="高危" :precision="0">
                <template #suffix>
                  <el-icon><Warning /></el-icon>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="6">
              <el-statistic :value="selectedReport?.vulnerabilityStats?.medium || 0" title="中危" :precision="0">
                <template #suffix>
                  <el-icon><InfoFilled /></el-icon>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="6">
              <el-statistic :value="selectedReport?.vulnerabilityStats?.low || 0" title="低危" :precision="0">
                <template #suffix>
                  <el-icon><CircleInfo /></el-icon>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </div>
        
        <div class="details-section">
          <h3>报告内容</h3>
          <div class="report-content-preview" v-if="selectedReport?.preview">
            <div v-html="selectedReport.preview"></div>
          </div>
          <div v-else class="no-preview">
            暂无预览内容
          </div>
        </div>
        
        <div class="details-section">
          <h3>报告配置</h3>
          <el-collapse>
            <el-collapse-item title="数据范围">
              <div class="collapse-content">
                <div v-if="selectedReport?.dataRangeType === 'scan_tasks'">
                  <p><strong>扫描任务:</strong></p>
                  <ul>
                    <li v-for="(task, index) in getScanTaskNames(selectedReport?.selectedScanTasks)" :key="index">
                      {{ task }}
                    </li>
                  </ul>
                </div>
                <div v-else-if="selectedReport?.dataRangeType === 'date_range'">
                  <p><strong>时间范围:</strong> {{ selectedReport?.dateRange?.[0] }} 至 {{ selectedReport?.dateRange?.[1] }}</p>
                </div>
                <div v-else-if="selectedReport?.dataRangeType === 'assets'">
                  <p><strong>资产:</strong></p>
                  <ul>
                    <li v-for="(asset, index) in getAssetNames(selectedReport?.selectedAssets)" :key="index">
                      {{ asset }}
                    </li>
                  </ul>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item title="筛选条件">
              <div class="collapse-content">
                <p><strong>严重程度:</strong> {{ getSeverityLabels(selectedReport?.severityFilter) }}</p>
                <p><strong>状态:</strong> {{ getStatusLabels(selectedReport?.statusFilter) }}</p>
              </div>
            </el-collapse-item>
            <el-collapse-item title="报告选项">
              <div class="collapse-content">
                <ul>
                  <li v-if="selectedReport?.includeStatistics">包含统计图表</li>
                  <li v-if="selectedReport?.includeRemediationTime">包含修复时间线</li>
                  <li v-if="selectedReport?.includeRiskScore">包含风险评分</li>
                  <li v-if="selectedReport?.anonymizeData">匿名化敏感数据</li>
                </ul>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        
        <div class="details-section" v-if="selectedReport?.fileUrls && Object.keys(selectedReport.fileUrls).length > 0">
          <h3>下载报告</h3>
          <div class="report-downloads">
            <el-button
              v-for="(url, format) in selectedReport.fileUrls"
              :key="format"
              type="primary"
              @click="downloadSpecificFormat(format, url)"
              :icon="getFormatIcon(format)"
              class="download-button"
            >
              下载 {{ getFormatLabel(format) }} 格式
            </el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showReportDetailsDialog = false">关闭</el-button>
          <el-button type="primary" v-if="selectedReport?.status === 'completed'" @click="downloadReport(selectedReport)">
            <el-icon><Download /></el-icon>
            下载报告
          </el-button>
          <el-button type="success" v-if="selectedReport?.status === 'completed'" @click="shareReport(selectedReport)">
            <el-icon><Share /></el-icon>
            分享报告
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享报告对话框 -->
    <el-dialog
      v-model="showShareReportDialog"
      title="分享报告"
      width="500px"
    >
      <el-form :model="shareForm">
        <el-form-item label="有效期">
          <el-radio-group v-model="shareForm.expiry">
            <el-radio :label="'1h'">1小时</el-radio>
            <el-radio :label="'1d'">1天</el-radio>
            <el-radio :label="'7d'">7天</el-radio>
            <el-radio :label="'30d'">30天</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="访问控制">
          <el-radio-group v-model="shareForm.accessControl">
            <el-radio :label="'public'">公开访问</el-radio>
            <el-radio :label="'password'">密码保护</el-radio>
            <el-radio :label="'email'">指定邮箱</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="shareForm.accessControl === 'password'" label="访问密码">
          <el-input
            v-model="shareForm.password"
            type="password"
            placeholder="请设置访问密码"
          />
        </el-form-item>
        
        <el-form-item v-if="shareForm.accessControl === 'email'" label="指定邮箱">
          <el-input
            v-model="shareForm.emails"
            type="textarea"
            placeholder="请输入允许访问的邮箱地址，多个邮箱用换行分隔"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="分享链接" v-if="shareForm.shareLink">
          <el-input
            v-model="shareForm.shareLink"
            readonly
            suffix-icon="CopyDocument"
            @click="copyShareLink"
          />
          <div class="share-tips">
            <el-icon><Warning /></el-icon>
            请妥善保管此链接，链接有效期至: {{ formatDateTime(shareForm.expiryDate) }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showShareReportDialog = false">关闭</el-button>
          <el-button type="primary" v-if="!shareForm.shareLink" @click="generateShareLink">生成分享链接</el-button>
          <el-button type="success" v-else @click="copyShareLink">复制链接</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 报告生成进度对话框 -->
    <el-dialog
      v-model="showGenerationProgressDialog"
      title="报告生成中"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      show-close="false"
    >
      <div class="generation-progress">
        <el-progress
          :percentage="generationProgress"
          :status="generationProgressStatus"
          :format="() => generationProgressText"
          :stroke-width="20"
          text-inside
        />
        <div class="progress-message">{{ generationMessage }}</div>
        <div class="estimated-time" v-if="estimatedTime">
          预计剩余时间: {{ estimatedTime }} 秒
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelReportGeneration" :disabled="generationProgressStatus === 'success'">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { Plus, Edit, Delete, Search, View, Download, Share, Refresh, CopyDocument, WarningFilled, Warning, InfoFilled, CircleInfo } from '@element-plus/icons-vue'

// 本地实现的日期格式化函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${formatDate(date)} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
}

// 模拟apiService
const apiService = {
  getSecurityReports: async () => [],
  createSecurityReport: async () => {},
  deleteSecurityReport: async () => {}
}

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const filterReportType = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const selectedReports = ref([])
const showCreateReportDialog = ref(false)
const showReportDetailsDialog = ref(false)
const showShareReportDialog = ref(false)
const showGenerationProgressDialog = ref(false)
const selectedReport = ref(null)
const reports = ref([])

// 生成进度相关
const generationProgress = ref(0)
const generationProgressStatus = ref('processing')
const generationProgressText = ref('')
const generationMessage = ref('')
const estimatedTime = ref(null)
const generationInterval = ref(null)

// 可用的扫描任务
const availableScanTasks = ref([
  { id: '1', name: '网站安全扫描 #1', completedAt: '2024-01-10T08:30:00Z' },
  { id: '2', name: 'API安全扫描 #1', completedAt: '2024-01-12T16:45:00Z' },
  { id: '3', name: '服务器漏洞扫描 #1', completedAt: '2024-01-08T14:20:00Z' },
  { id: '4', name: '数据库安全评估 #1', completedAt: '2024-01-15T11:30:00Z' },
  { id: '5', name: '内部网络扫描 #1', completedAt: '2024-01-13T14:45:00Z' }
])

// 可用的资产
const availableAssets = ref([
  { id: '1', name: 'web-app.example.com:443' },
  { id: '2', name: 'api.example.com:8080' },
  { id: '3', name: 'db.example.com:3306' },
  { id: '4', name: 'admin.example.com:8443' },
  { id: '5', name: 'blog.example.com:443' },
  { id: '6', name: 'download.example.com:443' },
  { id: '7', name: 'backend-service.example.com:8080' },
  { id: '8', name: 'user.example.com:443' },
  { id: '9', name: 'internal-api.example.com:8080' },
  { id: '10', name: 'api-admin.example.com:443' }
])

// 报告模板
const reportTemplates = ref([
  { id: '1', name: '标准安全报告模板' },
  { id: '2', name: '执行摘要报告模板' },
  { id: '3', name: '技术详细报告模板' },
  { id: '4', name: '合规评估报告模板' },
  { id: '5', name: '漏洞修复跟踪报告模板' }
])

// 创建报告表单
const createReportForm = reactive({
  name: '',
  description: '',
  type: 'scan',
  formats: ['pdf', 'html'],
  contentSections: ['executive_summary', 'vulnerability_summary', 'detailed_findings', 'remediation_guidance'],
  complianceStandards: [],
  dataRangeType: 'scan_tasks',
  selectedScanTasks: [],
  dateRange: [],
  selectedAssets: [],
  severityFilter: ['critical', 'high', 'medium', 'low'],
  statusFilter: ['new', 'confirmed', 'in_progress', 'fixed', 'verified', 'closed'],
  templateId: '',
  includeStatistics: true,
  includeRemediationTime: false,
  includeRiskScore: true,
  anonymizeData: false
})

// 分享表单
const shareForm = reactive({
  expiry: '7d',
  accessControl: 'public',
  password: '',
  emails: '',
  shareLink: '',
  expiryDate: null
})

// 表单验证规则
const createReportFormRules = {
  name: [
    { required: true, message: '请输入报告名称', trigger: 'blur' },
    { min: 3, max: 100, message: '报告名称长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '报告描述不能超过 500 个字符', trigger: 'blur' }
  ],
  formats: [
    { required: true, message: '请至少选择一种报告格式', trigger: 'change' }
  ],
  contentSections: [
    {
      required: () => createReportForm.type !== 'compliance',
      message: '请至少选择一个报告内容',
      trigger: 'change'
    }
  ],
  complianceStandards: [
    {
      required: () => createReportForm.type === 'compliance',
      message: '请至少选择一个合规标准',
      trigger: 'change'
    }
  ],
  severityFilter: [
    { required: true, message: '请至少选择一个严重程度', trigger: 'change' }
  ],
  statusFilter: [
    { required: true, message: '请至少选择一个状态', trigger: 'change' }
  ]
}

// 计算属性
const filteredReports = computed(() => {
  let result = [...reports.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(report => 
      report.name.toLowerCase().includes(query) ||
      (report.description && report.description.toLowerCase().includes(query))
    )
  }
  
  // 报告类型过滤
  if (filterReportType.value) {
    result = result.filter(report => report.type === filterReportType.value)
  }
  
  // 日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(report => {
      const reportDate = new Date(report.createdAt)
      return reportDate >= startDate && reportDate <= endDate
    })
  }
  
  return result
})

const paginatedReports = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredReports.value.slice(start, end)
})

// 方法
const loadReports = async () => {
  loading.value = true
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getSecurityReports()
    // reports.value = response
    
    // 模拟数据
    reports.value = [
      {
        id: 'REPORT-2024-0001',
        name: '2024年1月网站安全扫描报告',
        description: '对公司网站进行的全面安全扫描，包括漏洞扫描、配置检查和安全评估。',
        type: 'scan',
        formats: ['pdf', 'html', 'excel'],
        status: 'completed',
        createdAt: '2024-01-10T10:30:00Z',
        updatedAt: '2024-01-10T10:45:00Z',
        generatedBy: '1',
        generationTime: 45,
        vulnerabilityStats: {
          critical: 1,
          high: 3,
          medium: 5,
          low: 12
        },
        fileUrls: {
          pdf: '/reports/REPORT-2024-0001.pdf',
          html: '/reports/REPORT-2024-0001.html',
          excel: '/reports/REPORT-2024-0001.xlsx'
        },
        preview: '<h3>执行摘要</h3><p>本次扫描发现总计21个安全问题，其中1个严重级别，3个高危级别，5个中危级别和12个低危级别。建议优先修复严重和高危级别的漏洞。</p>'
      },
      {
        id: 'REPORT-2024-0002',
        name: 'API服务安全评估报告',
        description: '对公司API服务进行的安全评估，包括认证机制、授权控制、数据验证和加密传输等方面。',
        type: 'scan',
        formats: ['pdf', 'html'],
        status: 'completed',
        createdAt: '2024-01-12T16:45:00Z',
        updatedAt: '2024-01-12T17:05:00Z',
        generatedBy: '2',
        generationTime: 62,
        vulnerabilityStats: {
          critical: 0,
          high: 2,
          medium: 7,
          low: 9
        },
        fileUrls: {
          pdf: '/reports/REPORT-2024-0002.pdf',
          html: '/reports/REPORT-2024-0002.html'
        },
        preview: '<h3>执行摘要</h3><p>API服务安全评估发现18个安全问题，其中2个高危级别，7个中危级别和9个低危级别。主要问题集中在输入验证和错误处理方面。</p>'
      },
      {
        id: 'REPORT-2024-0003',
        name: '服务器漏洞聚合报告',
        description: '对所有服务器资产的漏洞进行聚合分析，提供整体安全状况评估。',
        type: 'vulnerability',
        formats: ['pdf', 'excel', 'json'],
        status: 'completed',
        createdAt: '2024-01-08T14:20:00Z',
        updatedAt: '2024-01-08T14:40:00Z',
        generatedBy: '3',
        generationTime: 38,
        vulnerabilityStats: {
          critical: 2,
          high: 5,
          medium: 12,
          low: 23
        },
        fileUrls: {
          pdf: '/reports/REPORT-2024-0003.pdf',
          excel: '/reports/REPORT-2024-0003.xlsx',
          json: '/reports/REPORT-2024-0003.json'
        },
        preview: '<h3>执行摘要</h3><p>服务器漏洞聚合分析显示共有42个安全问题，其中2个严重级别，5个高危级别，12个中危级别和23个低危级别。需要立即处理严重级别的漏洞。</p>'
      },
      {
        id: 'REPORT-2024-0004',
        name: 'PCI DSS合规评估报告',
        description: '根据PCI DSS 4.0标准对支付系统进行的合规性评估。',
        type: 'compliance',
        formats: ['pdf', 'html'],
        status: 'completed',
        createdAt: '2024-01-15T11:30:00Z',
        updatedAt: '2024-01-15T12:15:00Z',
        generatedBy: '4',
        generationTime: 125,
        complianceStandards: ['pci_dss'],
        complianceStats: {
          passed: 12,
          failed: 3,
          not_applicable: 5
        },
        fileUrls: {
          pdf: '/reports/REPORT-2024-0004.pdf',
          html: '/reports/REPORT-2024-0004.html'
        },
        preview: '<h3>PCI DSS合规摘要</h3><p>本次评估基于PCI DSS 4.0标准，检查了20项控制点，其中12项通过，3项未通过，5项不适用。需要对未通过的控制点进行整改。</p>'
      },
      {
        id: 'REPORT-2024-0005',
        name: '内部网络安全状态报告',
        description: '内部网络资产安全状态月度报告，包括漏洞统计、修复进度和安全建议。',
        type: 'custom',
        formats: ['pdf', 'html', 'excel'],
        status: 'completed',
        createdAt: '2024-01-13T14:45:00Z',
        updatedAt: '2024-01-13T15:20:00Z',
        generatedBy: '1',
        generationTime: 85,
        vulnerabilityStats: {
          critical: 0,
          high: 1,
          medium: 8,
          low: 15
        },
        fileUrls: {
          pdf: '/reports/REPORT-2024-0005.pdf',
          html: '/reports/REPORT-2024-0005.html',
          excel: '/reports/REPORT-2024-0005.xlsx'
        },
        preview: '<h3>内部网络安全摘要</h3><p>内部网络资产安全评估发现24个安全问题，其中1个高危级别，8个中危级别和15个低危级别。整体安全状况良好，但仍需关注高危漏洞。</p>'
      },
      {
        id: 'REPORT-2024-0006',
        name: '季度安全状况综合报告',
        description: '2023年第四季度安全状况综合报告，包括漏洞趋势、修复进度和安全建议。',
        type: 'custom',
        formats: ['pdf', 'html'],
        status: 'processing',
        createdAt: '2024-01-16T09:00:00Z',
        updatedAt: '2024-01-16T09:15:00Z',
        generatedBy: '3',
        progress: 65
      },
      {
        id: 'REPORT-2024-0007',
        name: '新上线应用安全评估报告',
        description: '对新上线的用户管理系统进行的安全评估，包括功能测试和安全扫描。',
        type: 'scan',
        formats: ['pdf'],
        status: 'queued',
        createdAt: '2024-01-16T10:30:00Z',
        updatedAt: '2024-01-16T10:30:00Z',
        generatedBy: '2'
      }
    ]
  } catch (error) {
    console.error('加载安全报告失败:', error)
    ElMessage.error('加载安全报告失败，请重试')
  } finally {
    loading.value = false
  }
}

const getReportTypeTag = (type) => {
  const typeMap = {
    'scan': 'primary',
    'vulnerability': 'success',
    'compliance': 'warning',
    'custom': 'info'
  }
  return typeMap[type] || 'default'
}

const getReportTypeLabel = (type) => {
  const labelMap = {
    'scan': '扫描报告',
    'vulnerability': '漏洞聚合报告',
    'compliance': '合规报告',
    'custom': '自定义报告'
  }
  return labelMap[type] || type
}

const getReportStatusTag = (status) => {
  const statusMap = {
    'queued': 'info',
    'processing': 'primary',
    'completed': 'success',
    'failed': 'danger'
  }
  return statusMap[status] || 'default'
}

const getReportStatusLabel = (status) => {
  const labelMap = {
    'queued': '排队中',
    'processing': '生成中',
    'completed': '已完成',
    'failed': '失败'
  }
  return labelMap[status] || status
}

const getFormatLabel = (format) => {
  const labelMap = {
    'pdf': 'PDF',
    'html': 'HTML',
    'excel': 'Excel',
    'json': 'JSON'
  }
  return labelMap[format] || format.toUpperCase()
}

const getFormatIcon = (format) => {
  // 这里可以返回对应格式的图标
  return null
}

const getUserName = (userId) => {
  const userMap = {
    '1': '张三',
    '2': '李四',
    '3': '王五',
    '4': '赵六',
    '5': '孙七'
  }
  return userMap[userId] || '未知用户'
}

const getUserAvatar = (userId) => {
  // 这里可以返回用户头像URL
  return ''
}

const getUserInitial = (userId) => {
  return getUserName(userId).charAt(0)
}

const truncateText = (text, maxLength) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const getScanTaskNames = (taskIds) => {
  if (!taskIds || taskIds.length === 0) return []
  return taskIds.map(id => {
    const task = availableScanTasks.value.find(t => t.id === id)
    return task ? task.name : id
  })
}

const getAssetNames = (assetIds) => {
  if (!assetIds || assetIds.length === 0) return []
  return assetIds.map(id => {
    const asset = availableAssets.value.find(a => a.id === id)
    return asset ? asset.name : id
  })
}

const getSeverityLabels = (severities) => {
  if (!severities || severities.length === 0) return '-'
  const severityMap = {
    'critical': '严重',
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  }
  return severities.map(s => severityMap[s] || s).join(', ')
}

const getStatusLabels = (statuses) => {
  if (!statuses || statuses.length === 0) return '-'
  const statusMap = {
    'new': '待确认',
    'confirmed': '已确认',
    'in_progress': '处理中',
    'fixed': '已修复',
    'verified': '已验证',
    'closed': '已关闭'
  }
  return statuses.map(s => statusMap[s] || s).join(', ')
}

const resetCreateReportForm = () => {
  Object.assign(createReportForm, {
    name: '',
    description: '',
    type: 'scan',
    formats: ['pdf', 'html'],
    contentSections: ['executive_summary', 'vulnerability_summary', 'detailed_findings', 'remediation_guidance'],
    complianceStandards: [],
    dataRangeType: 'scan_tasks',
    selectedScanTasks: [],
    dateRange: [],
    selectedAssets: [],
    severityFilter: ['critical', 'high', 'medium', 'low'],
    statusFilter: ['new', 'confirmed', 'in_progress', 'fixed', 'verified', 'closed'],
    templateId: '',
    includeStatistics: true,
    includeRemediationTime: false,
    includeRiskScore: true,
    anonymizeData: false
  })
}

const createReport = async () => {
  // 验证表单
  const createReportFormRef = ref(null)
  if (!createReportFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.createSecurityReport(createReportForm)
    
    // 模拟报告生成过程
    showCreateReportDialog.value = false
    showGenerationProgressDialog.value = true
    
    // 重置进度
    generationProgress.value = 0
    generationProgressStatus.value = 'processing'
    generationProgressText.value = '准备中...'
    generationMessage.value = '正在初始化报告生成任务...'
    estimatedTime.value = 60 // 预估60秒
    
    // 模拟进度更新
    let currentProgress = 0
    let steps = [
      { progress: 10, message: '正在收集数据...', text: '10%' },
      { progress: 30, message: '正在分析漏洞数据...', text: '30%' },
      { progress: 50, message: '正在生成统计图表...', text: '50%' },
      { progress: 70, message: '正在生成PDF报告...', text: '70%' },
      { progress: 85, message: '正在生成HTML报告...', text: '85%' },
      { progress: 100, message: '报告生成完成', text: '100%' }
    ]
    
    let stepIndex = 0
    generationInterval.value = setInterval(() => {
      currentProgress += 2
      generationProgress.value = currentProgress
      estimatedTime.value = Math.max(0, estimatedTime.value - 2)
      
      if (stepIndex < steps.length && currentProgress >= steps[stepIndex].progress) {
        generationProgressText.value = steps[stepIndex].text
        generationMessage.value = steps[stepIndex].message
        stepIndex++
      }
      
      if (currentProgress >= 100) {
        clearInterval(generationInterval.value)
        generationProgressStatus.value = 'success'
        
        // 模拟添加新报告
        const newReport = {
          id: `REPORT-${new Date().getFullYear()}-${String(reports.value.length + 1).padStart(4, '0')}`,
          name: createReportForm.name,
          description: createReportForm.description,
          type: createReportForm.type,
          formats: createReportForm.formats,
          status: 'completed',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          generatedBy: '1', // 当前用户ID，实际应该从用户认证信息获取
          generationTime: 60,
          vulnerabilityStats: {
            critical: Math.floor(Math.random() * 3),
            high: Math.floor(Math.random() * 5) + 1,
            medium: Math.floor(Math.random() * 10) + 3,
            low: Math.floor(Math.random() * 20) + 5
          },
          fileUrls: {},
          preview: `<h3>执行摘要</h3><p>本报告包含了根据您的配置生成的安全分析结果。报告生成时间: ${formatDateTime(new Date().toISOString())}</p>`
        }
        
        // 添加文件URL
        createReportForm.formats.forEach(format => {
          newReport.fileUrls[format] = `/reports/${newReport.id}.${format === 'excel' ? 'xlsx' : format}`
        })
        
        reports.value.unshift(newReport)
        
        setTimeout(() => {
          showGenerationProgressDialog.value = false
          ElNotification({
            title: '成功',
            message: '报告生成成功',
            type: 'success'
          })
        }, 1000)
      }
    }, 2000) // 每2秒更新一次进度
    
  } catch (error) {
    console.error('创建报告失败:', error)
    ElMessage.error('创建报告失败，请重试')
    showGenerationProgressDialog.value = false
    if (generationInterval.value) {
      clearInterval(generationInterval.value)
    }
  }
}

const cancelReportGeneration = () => {
  ElMessageBox.confirm(
    '确定要取消报告生成吗？',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    if (generationInterval.value) {
      clearInterval(generationInterval.value)
    }
    showGenerationProgressDialog.value = false
    ElMessage.success('已取消报告生成')
  }).catch(() => {
    // 用户取消操作
  })
}

const viewReportDetails = (report) => {
  selectedReport.value = report
  showReportDetailsDialog.value = true
}

const downloadReport = (report) => {
  // 默认下载PDF格式
  const pdfUrl = report.fileUrls?.pdf
  if (pdfUrl) {
    // 这里应该实现真实的文件下载
    ElMessage.success('报告下载中...')
    console.log('下载报告:', pdfUrl)
  } else {
    ElMessage.warning('PDF格式报告不可用')
  }
}

const downloadSpecificFormat = (format, url) => {
  // 这里应该实现真实的文件下载
  ElMessage.success(`${getFormatLabel(format)}格式报告下载中...`)
  console.log('下载报告:', url)
}

const shareReport = (report) => {
  selectedReport.value = report
  // 重置分享表单
  Object.assign(shareForm, {
    expiry: '7d',
    accessControl: 'public',
    password: '',
    emails: '',
    shareLink: '',
    expiryDate: null
  })
  showShareReportDialog.value = true
}

const generateShareLink = async () => {
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.generateReportShareLink(selectedReport.value.id, shareForm)
    
    // 模拟生成分享链接
    const now = new Date()
    let expiryMs = 0
    switch (shareForm.expiry) {
      case '1h': expiryMs = 3600000; break
      case '1d': expiryMs = 86400000; break
      case '7d': expiryMs = 604800000; break
      case '30d': expiryMs = 2592000000; break
    }
    
    const expiryDate = new Date(now.getTime() + expiryMs)
    shareForm.expiryDate = expiryDate.toISOString()
    shareForm.shareLink = `https://example.com/share/report/${selectedReport.value.id}?token=mock-token-${Math.random().toString(36).substr(2, 9)}`
    
    ElMessage.success('分享链接生成成功')
  } catch (error) {
    console.error('生成分享链接失败:', error)
    ElMessage.error('生成分享链接失败，请重试')
  }
}

const copyShareLink = () => {
  if (shareForm.shareLink) {
    // 复制到剪贴板
    navigator.clipboard.writeText(shareForm.shareLink).then(() => {
      ElMessage.success('链接已复制到剪贴板')
    }).catch(() => {
      ElMessage.error('复制失败，请手动复制')
    })
  }
}

const deleteReport = async (report) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除报告"${report.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )
    
    // 这里模拟API调用，实际项目中应该调用真实API
    // await apiService.deleteSecurityReport(report.id)
    
    // 从列表中移除
    const index = reports.value.findIndex(r => r.id === report.id)
    if (index !== -1) {
      reports.value.splice(index, 1)
    }
    
    ElMessage.success('报告删除成功')
  } catch (error) {
    // 用户取消操作或删除失败
  }
}

const refreshReports = () => {
  loadReports()
  ElMessage.success('数据已刷新')
}

const handleSelectionChange = (selection) => {
  selectedReports.value = selection
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchQuery.value = ''
  filterReportType.value = ''
  dateRange.value = []
  currentPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newCurrent) => {
  currentPage.value = newCurrent
}

// 初始化
onMounted(() => {
  loadReports()
})
</script>

<style scoped>
.security-reporting-container {
  padding: 20px;
}

.reporting-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.report-list-container {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.report-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.report-name {
  font-weight: 500;
  color: #303133;
}

.report-description {
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
}

.report-formats {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.format-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.vulnerability-stats {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.critical-count {
  color: #f56c6c;
  font-weight: 500;
}

.high-count {
  color: #e6a23c;
  font-weight: 500;
}

.medium-count {
  color: #409eff;
  font-weight: 500;
}

.low-count {
  color: #67c23a;
  font-weight: 500;
}

.generated-by {
  display: flex;
  align-items: center;
  gap: 6px;
}

.report-details {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.details-section {
  margin-bottom: 20px;
}

.details-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.report-content-preview {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.report-content-preview h3 {
  margin-top: 0;
  font-size: 16px;
  color: #303133;
  border-bottom: none;
  padding-bottom: 0;
}

.no-preview {
  color: #909399;
  text-align: center;
  padding: 40px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.collapse-content {
  padding: 8px 0;
}

.collapse-content p {
  margin: 8px 0;
}

.collapse-content ul {
  margin: 8px 0;
  padding-left: 20px;
}

.collapse-content li {
  margin: 4px 0;
}

.report-downloads {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.download-button {
  margin-bottom: 8px;
}

.share-tips {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #e0f2fe;
  border-radius: 4px;
  font-size: 13px;
  color: #0284c7;
  display: flex;
  align-items: center;
  gap: 6px;
}

.generation-progress {
  padding: 20px 0;
}

.progress-message {
  text-align: center;
  margin: 16px 0;
  color: #606266;
}

.estimated-time {
  text-align: center;
  color: #909399;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .vulnerability-stats {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 768px) {
  .security-reporting-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-filter-container .el-row {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .search-filter-container .el-col {
    width: 100%;
  }
  
  .vulnerability-stats {
    flex-direction: row;
    justify-content: space-around;
  }
  
  .report-downloads {
    flex-direction: column;
  }
  
  .download-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .generated-by {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}
</style>